// 用户模块
import { login as loginAPI, logout as logoutAPI, getUserInfo } from '@/api/auth'

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}

const mutations = {
  // 设置token
  SET_TOKEN (state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  // 设置用户信息
  SET_USER_INFO (state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },
  // 清空用户信息
  CLEAR_USER_INFO (state) {
    state.token = ''
    state.userInfo = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
}

const actions = {
  // 登录
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginAPI(userInfo).then(response => {
        const { token, userInfo: userData } = response.data
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', userData)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出登录
  logout ({ commit }) {
    return new Promise((resolve, reject) => {
      logoutAPI().then(() => {
        commit('CLEAR_USER_INFO')
        resolve()
      }).catch(error => {
        // 即使退出登录接口失败，也清除本地用户信息
        commit('CLEAR_USER_INFO')
        reject(error)
      })
    })
  },
  // 获取用户信息
  getUserInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        commit('SET_USER_INFO', response.data)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
